import { session } from 'js/util'
import { apiQueryCustomerByStoreId, apiQueryCustomerByPhoneNumber } from 'js/api'
export default {
  state: {
    appkey: '43fe9b8de1d5f3934eebf713',
    secret: '2032ab56604aa09b109938eb',
    JIMVisible: false,
    JIMUserList: [],
    JIMTargetUser: {}, // 当前聊天对象和客服信息
    newMsgByBuyer: false,
    StoreUserList: [],
    StoreTargetUser: {}
  },
  getters: {
    appkey: state => state.appkey,
    secret: state => state.secret,
    JIMVisible: state => state.JIMVisible,
    JIMUserList: state => state.JIMUserList,
    JIMTargetUser: state => state.JIMTargetUser,
    newMsgByBuyer: state => state.newMsgByBuyer,
    StoreUserList: state => state.StoreUserList,
    StoreTargetUser: state => state.StoreTargetUser
  },
  actions: {
    // JMessage初始化
    JIMInit({ state }, payload) {
      // 初始化数据  timestamp 时间戳 random_str 随机字符串 signature 签名，需md5加密
      const timestamp = (new Date()).valueOf()
      const randomStr = '022cd9fd995849b58b3ef0e943421ed9'
      const signature = md5(`appkey=${state.appkey}&timestamp=${timestamp}&random_str=${randomStr}&key=${state.secret}`)

      // 初始化
      JIM.init({
        'appkey': state.appkey,
        'random_str': randomStr,
        'signature': signature,
        'timestamp': timestamp,
        'flag': 1
      }).onSuccess(data => {
        // 初始化成功的时候，需要去进行操作
        payload.onSuccess && payload.onSuccess(data)
      })
    },
    // 根据店铺Id获取客服信息
    fetchCustomerByStoreId({ state, commit }, payload) {
      apiQueryCustomerByStoreId(payload.storeId, payload.mobile).then(data => {
        data = data || {}
        // 打开聊天框
        commit('showJIMVisible')
        // 如果和目标对象相同改，则不进行操作
        // if (data.adminId == state.JIMTargetUser.adminId) return
        // 发送者信息集合
        const fromUser = session.get('userInfo') || {}
        // 把取回的值，转化成发送消息时需要的格式
        const newUser = {
          adminId: data.adminId, // 平台创建ID
          goodsId: payload.goodsId || '', // 商品Id
          storeId: data.storeId, // 店铺id
          buyName: fromUser.nickName, // 买家名称
          buyImg: fromUser.userHeadImg, // 买家头像
          buyId: fromUser.mobile, // 买家手机号
          storeName: data.storeName, // 店铺名称
          storeLogo: data.storeLogo, // 店铺头像
          customerPhone: data.customerPhone, // 客服手机号
          storePhone: data.storePhone, // 店铺拥有者的手机号
          message: [],
          firstMsg: payload.firstMsg
        }
        commit('setTargetUser', {
          user: newUser
        })
      })
    },

    // 根据手机号码获取客服信息
    fetchCustomerByPhoneNumber({ state, commit }, payload) {
      apiQueryCustomerByPhoneNumber(payload.mobile).then(data => {
        data = data || {}
        // 打开聊天框
        commit('showJIMVisible')
        // 如果和目标对象相同改，则不进行操作
        // if (data.adminId == state.JIMTargetUser.adminId) return
        // 发送者信息集合
        const fromUser = session.get('userInfo') || {}
        // 把取回的值，转化成发送消息时需要的格式
        const newUser = {
          adminId: data.adminId, // 平台创建ID
          // goodsId: payload.goodsId || '', // 商品Id
          // storeId: data.storeId, // 店铺id
          buyName: fromUser.nickName, // 买家名称
          buyImg: fromUser.userHeadImg, // 买家头像
          buyId: fromUser.mobile, // 买家手机号
          storeName: data.storeName, // 客服名称
          storeLogo: data.storeLogo, // 客服头像
          customerPhone: data.customerPhone, // 客服手机号
          // storePhone: data.storePhone, // 店铺拥有者的手机号
          message: [],
          firstMsg: payload.firstMsg
        }
        commit('setTargetUser', {
          user: newUser
        })
      })
    }
  },
  mutations: {
    // 隐藏聊天框
    hideJIMVisible(state) {
      state.newMsgByBuyer = false
      state.JIMVisible = false
    },
    // 打开聊天框
    showJIMVisible(state) {
      state.JIMVisible = true
    },
    // 设置用户消息列表
    setJIMUserList(state, payload) {
      state.JIMUserList = payload
    },
    // 切换目标聊天用户
    setTargetUser(state, payload) {
      if (payload.user.length) {
        let existUser = null
        payload.user.forEach((user, i) => {
          if (user.storeId == state.JIMTargetUser.storeId) {
            existUser = payload.user.splice(i, 1)[0]
            return
          }
        })
        if (existUser) {
          existUser.customerPhone = existUser.customerPhone ? existUser.customerPhone : state.JIMTargetUser.customerPhone
          existUser.goodsId = existUser.goodsId ? existUser.goodsId : state.JIMTargetUser.goodsId
          payload.user.unshift(existUser)
          state.JIMUserList = payload.user
        } else {
          if (state.JIMTargetUser.adminId) {
            payload.user.unshift(state.JIMTargetUser)
            state.JIMUserList = payload.user
          } else {
            state.JIMUserList = payload.user
          }
        }
        state.JIMTargetUser = state.JIMUserList[0]
      } else { // 如果是对象，取到的是点击商家的数据
        // 点击左侧聊天切换
        if (payload.select) {
          let existIndex = state.JIMUserList.findIndex(item => {
            return item.storeId == payload.user.storeId
          })
          state.JIMTargetUser = state.JIMUserList[existIndex]
        // 点击店铺或商品
        } else {
          // 判断用户是否存在
          let existUser = null
          state.JIMUserList.forEach((user, i) => {
            if (user.storeId == payload.user.storeId) {
              existUser = state.JIMUserList.splice(i, 1)[0]
              return
            }
          })
          if (existUser) {
            existUser.firstMsg = payload.user.firstMsg
          }
          existUser = !existUser ? payload.user : existUser
          state.JIMUserList.unshift(existUser)
          state.JIMTargetUser = state.JIMUserList[0]
        }
      }
    },
    // 平台销售设置用户列表
    setStoreUserList(state, payload) {
      state.StoreUserList = payload
    },
    // 平台销售设置目标用户
    setStoreTargetUser(state, payload) {
      state.StoreTargetUser = payload
    },
    setNewMsgByBuyer(state, payload) {
      state.newMsgByBuyer = payload
    }
  }
}